<?php

namespace app\home\controller;

use app\common\CustomerContactsModel;
use app\common\CustomerModel;
use app\common\CustomerRecordModel;
use think\Db;
use think\Request;
use think\Validate;

class CustomerController extends BaseController
{
    private $customerModel;
    private $customerContactsModel;
    private $customerRecordModel;
    private $userInfo;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->customerModel = new CustomerModel();
        $this->customerContactsModel = new CustomerContactsModel();
        $this->customerRecordModel = new CustomerRecordModel();
        $this->userInfo = $this->getDduser();
    }

    //我的客户
    public function index()
    {
        $map = ['owner_userid' => $this->userInfo['userid']];
        $data = $this->request->param();
        if (!empty($data['rating'])) {
            $map['rating'] = $data['rating'];
        }
        if (!empty($data['name'])) {
            $map['name'] = ['like', '%' . $data['name'] . '%'];
        }
        $startTime = $this->request->param('start_time', '1970-01-01 08:00:01');
        $endTime = $this->request->param('end_time', '5138-11-16 17:46:39');
        $map['create_time'] = ['between', [strtotime($startTime), strtotime($endTime)]];
        $list = $this->customerModel->where($map)->paginate(12, false, ['query' => $data]);
        return $this->callBack(0, '', $list);
    }

    /**
     * 添加客户,如果添加公海客户需要将is_public设置为1
     * @param array $data
     * @return array|\think\response\Json
     */
    public function add($data = [])
    {
        if (empty($data)) {
            $data = $this->request->param();
        }
        $data['owner_userid'] = $this->userInfo['userid'];
        $data['creator_userid'] = $this->userInfo['userid'];
        $validate = new Validate([
            ['creator_userid', 'require', '请先登陆'],
            ['telephone', 'require', '请输入联系方式'],
            ['name', 'require', '请填写客户名字'],
            ['rating', 'require', '请选择客户等级'],
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            return $this->callBack(1, $validate->getError());
        }
        $contacts = $this->addContacts($data);
        if ($contacts['status'] > 0) {
            return $this->callBack($contacts['status'], $contacts['msg']);
        }
        $data['contacts_id'] = $contacts['data'];
        if (!empty($data['is_public']) && $data['is_public'] == 1) {
            unset($data['owner_userid']);
        }
        if ($this->customerModel->data($data)->allowField(true)->save()) {
            $customerId = $this->customerModel->getLastInsID();
            $record[] = ['customer_id' => $customerId, 'userid' => $this->userInfo['userid'], 'create_time' => time(), 'type' => 1];
            if (empty($data['is_public']) || $data['is_public'] == 0) {
                $record[] = ['customer_id' => $customerId, 'userid' => $this->userInfo['userid'], 'create_time' => time(), 'type' => 2];
            }
            $this->customerRecordModel->allowField(true)->saveAll($record);
            return $this->callBack(0, '客户添加成功', $customerId);
        } else {
            return $this->callBack(2, '客户添加失败');
        }
    }

    /**
     * 修改客户信息
     * @return array|\think\response\Json
     */
    public function edit()
    {
        $data['creator_userid'] = $this->userInfo['userid'];
        $validate = new Validate([
            ['customer_id', 'require', '请选择客户'],
            ['creator_userid', 'require', '请先登陆'],
            ['telephone', 'require', '请输入联系方式'],
            ['name', 'require', '请填写客户名字'],
            ['rating', 'require', '请选择客户等级'],
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            return $this->callBack(1, $validate->getError());
        }
        $customerInfo = $this->customerModel->where('customer_id', $data['customer_id'])->find();
        $data['contacts_id'] = $customerInfo['contacts_id'];
        $contacts = $this->editContacts($data);
        if ($contacts['status'] > 0) {
            return $this->callBack($contacts['status'], $contacts['msg']);
        }
        $data['contacts_id'] = $contacts['data'];
        if ($this->customerModel->data($data)->allowField(true)->save()) {
            return $this->callBack(0, '客户修改成功', $data['customer_id']);
        } else {
            return $this->callBack(2, '客户修改失败');
        }
    }

    /**
     * 领取或者分配客户
     */
    public function distribution()
    {
        $data = $this->request->param();
        $validate = new Validate([
            ['customer_id', 'require', '请选择客户'],
            ['userid', 'require', '请指定负责人'],
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            return $this->callBack(1, $validate->getError());
        }
        if ($data['userid'] == $this->userInfo['userid']) {
            $data['type'] = 2;
        } else {
            $data['type'] = 3;
        }
        if ($this->customerModel->where(['customer_id' => $data['customer_id'], 'owner_userid' => ''])->setField('owner_userid', $data['userid'])) {
            $this->customerRecordModel->data($data)->save();
            return $this->callBack(0, '用户' . $data['type'] == 2 ? '领取' : '分配' . '成功',$data['customer_id']);
        } else {
            return $this->callBack(0, '用户' . $data['type'] == 2 ? '领取' : '分配' . '失败');
        }
    }

    /**
     * 放弃客户
     * @return array|\think\response\Json
     */
    public function giveUp()
    {
        $customerId=$this->request->param('customer_id',0);
        if ($this->customerModel->where(['customer_id'=>$customerId,'owner_userid'=>$this->userInfo['owner_userid']])->setField('owner_userid','')){
            return $this->callBack(0,'该客户已经放弃');
        }else{
            return $this->callBack(2,$this->customerModel->getError());
        }
    }

    /**
     * 获取客户联系人列表
     */
    public function contacts()
    {
        $customerId = $this->request->param('customer_id', 0);
        $list = $this->customerContactsModel->where('customer_id', $customerId)->paginate();
        return $this->callBack(0, '', $list);
    }

    /**
     * 获取客户联系人详情
     */
    public function contactsInfo()
    {
        $contactsId = $this->request->param('contacts_id', 0);
        $info = $this->customerContactsModel->where('contacts_id', $contactsId)->find();
        return $this->callBack(0, '', $info);
    }

    /**
     * 添加客户联系人
     */
    public function addContacts($data = [])
    {
        $isJson = 0;
        if (empty($data)) {
            $data = $this->request->param();
            $isJson = 1;
        }
        $data['creator_role_id'] = $this->userInfo['userid'];
        $validate = new Validate([
            ['creator_role_id', 'require', '请先登陆'],
            ['name', 'require', '请输入联系人姓名'],
            ['telephone', 'require', '请输入联系方式']
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            return $this->callBack(1, $validate->getError(), [], $isJson);
        }
        if ($this->customerContactsModel->data($data)->allowField(true)->save()) {
            return $this->callBack(0, '联系人添加成功', $this->customerContactsModel->getLastInsID(), $isJson);
        } else {
            return $this->callBack(2, $this->customerContactsModel->getError(), [], $isJson);
        }
    }

    /**
     * 修改客户联系人
     */
    public function editContacts($data = [])
    {
        $isJson = 0;
        if (empty($data)) {
            $data = $this->request->param();
            $isJson = 1;
        }
        $data['creator_role_id'] = $this->userInfo['userid'];
        $validate = new Validate([
            ['contacts_id', 'require', '请选择要修改的联系人'],
            ['creator_role_id', 'require', '请先登陆'],
            ['name', 'require', '请输入联系人姓名'],
            ['telephone', 'require', '请输入联系方式']
        ]);
        $result = $validate->check($data);
        if (true !== $result) {
            return $this->callBack(1, $validate->getError(), [], $isJson);
        }
        if ($this->customerContactsModel->data($data)->allowField(true)->save()) {
            return $this->callBack(0, '联系人修改成功', $data['contacts_id'], $isJson);
        } else {
            return $this->callBack(2, $this->customerContactsModel->getError(), [], $isJson);
        }
    }

    /**
     * 设置为首要联系人
     */
    public function setMain()
    {
        $data=$this->request->param();
        $validate=new Validate([
            ['customer_id','require','请选择要设置的客户'],
            ['contacts_id','require','请选择要设置的联系人']
        ]);
        $result=$validate->check($data);
        if (true!==$result){
            return $this->callBack(1,$validate->getError());
        }
        if (!$this->customerContactsModel->where(['customer_id'=>$data['customer_id'],'contacts_id'=>$data['contacts_id']])->count()){
            return $this->callBack(1,'选择的联系人不是选择的客户的联系人');
        }
        if ($this->customerModel->where(['customer_id'=>$data['customer_id']])->setField('contacts_id',$data['contacts_id'])){
            return $this->callBack(0,'首要联系人设置成功',$data['customer_id']);
        }else{
            return $this->callBack(2,$this->customerModel->getError());
        }
    }

    /**
     * 删除客户联系人
     */
    public function delContacts()
    {
        $contactsId = $this->request->param('contacts_id', 0);
        if ($this->customerContactsModel->where('contacts_id', $contactsId)->data(['is_deleted'=>1,'delete_userid'=>$this->userInfo['userid'],'delete_time'=>time()])->save()) {
            return $this->callBack(0, '联系人删除成功');
        } else {
            return $this->callBack(2, $this->customerContactsModel->getError());
        }
    }
}
